/**
 * Copyright (c) 2017 ucsmy.com, All rights reserved.
 */
package itsm.isperp.module.controller.api.wechat.v2;

import itsm.isperp.framework.core.context.ContextHolder;
import itsm.isperp.framework.domain.IUser;
import itsm.isperp.framework.web.request.JqGridFilterRuleOp;
import itsm.isperp.framework.web.request.JqGridRequest;
import itsm.isperp.module.entity.app.AppDepartment;
import itsm.isperp.module.entity.app.AppDict;
import itsm.isperp.module.entity.app.AppUser;
import itsm.isperp.module.entity.configuration.ConfCategory;
import itsm.isperp.module.entity.incident.IcdCategory;
import itsm.isperp.module.entity.serviceCatalog.SrcCategory;
import itsm.isperp.module.service.app.AppDepartmentService;
import itsm.isperp.module.service.app.AppDictService;
import itsm.isperp.module.service.app.AppUserService;
import itsm.isperp.module.service.configuration.ConfCategoryService;
import itsm.isperp.module.service.configuration.ConfCiService;
import itsm.isperp.module.service.incident.IcdCategoryService;
import itsm.isperp.module.service.serviceCatalog.SrcCategoryService;
import itsm.isperp.module.service.serviceCatalog.SrcServiceService;
import itsm.isperp.workflow.service.BpmProcessRunService;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Sort;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.MessageDigest;
import java.text.Collator;
import java.util.*;

/**
 * @Description:
 * @Author: legen
 * @Created Date: 2017-09-18-0018.
 * @LastModifyDate: 2017-09-18-0018.
 * @LastModifyBy: legen
 * @Version:
 */
@Controller
@RequestMapping("api/wechat/v2/common")
public class CommonController extends BaseController {

    private static final Logger logger = LoggerFactory.getLogger(CommonController.class);

    /**
     * 获取当前用户
     */
    @RequestMapping("userInfo")
    @ResponseBody
    public AppUser userInfo(String username) {

        AppUser appUser = this.appUserService.findByUsername(username, "name", "fullname");
        return appUser;
    }

    @Autowired
    private AppDictService appDictService;

    @RequestMapping("dict")
    @ResponseBody
    public List<AppDict> dict(String typeCode) throws InterruptedException {
        List<AppDict> dicts = appDictService.findByType(typeCode);
        return dicts;
    }

    @Autowired
    private IcdCategoryService icdCategoryService;

    /**
     * 获取事件分类
     */
    @RequestMapping("category")
    @ResponseBody
    public List<IcdCategory> category(String username) throws Exception {
        try {
            List<IcdCategory> tree = icdCategoryService.getTree(null, false, "id", "name", "parentId", "treenodePath");
            return tree;
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new Exception("获取事件分类失败，原因是：" + e.getMessage());
        }
    }

    @Autowired
    private SrcCategoryService srcCategoryService;

    @Autowired
    private SrcServiceService srcServiceService;

    /**
     * 获取服务目录
     */
    @RequestMapping("serviceCategory")
    @ResponseBody
    public List<SrcCategory> serviceCategory(String username) throws Exception {
        try {
            List<SrcCategory> tree = srcCategoryService.getTree(null, false, "id", "name", "parentId", "treenodePath");
            return tree;
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new Exception("获取服务目录失败，原因是：" + e.getMessage());
        }
    }

    /**
     * 获取服务目录
     */
    @RequestMapping("serviceService")
    @ResponseBody
    public List<Map<String, Object>> serviceService(String username, String category_path) throws Exception {
        try {
            JqGridRequest request = new JqGridRequest();
            request.addFilterRule("status", JqGridFilterRuleOp.eq, "发布");
            request.addFilterRule("treenode_path", JqGridFilterRuleOp.bw, category_path);
            request.setPageable(false);
            request.setSelectColumns("id", "code", "name");
            request.setSort("code", Sort.Direction.ASC);

            List<Map<String, Object>> list = srcServiceService.findAllDetailByRequest(request).getContent();
            super.addNullColumns(request, list);
            return list;
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new Exception("获取服务目录失败，原因是：" + e.getMessage());
        }
    }

    /**
     * 获取部门
     */
    @RequestMapping("department")
    @ResponseBody
    public List<AppDepartment> department(String username) {
        List<AppDepartment> tree = appDepartmentService.getTree(null, false, "id", "name", "parent_id", "treenodePath");
        return tree;
    }
    
    @RequestMapping("customerDepartment")
    @ResponseBody
    public List<AppDepartment> customerDepartment(String username) {
        List<AppDepartment> tree = appDepartmentService.getTree("38007504311542390162", false, "id", "name", "parent_id", "treenodePath");
        return tree;
    }
    
    @RequestMapping("userDepartment")
    @ResponseBody
    public List<AppDepartment> userDepartment(String username) {
        List<AppDepartment> tree = appDepartmentService.getTree("38007504311542390162", false, "id", "name", "parent_id", "treenodePath");
        return tree;
    }

    /**
     * 获取用户
     */
    @RequestMapping("user")
    @ResponseBody
    public List<Map<String, Object>> user(String username, String department_path) {
        JqGridRequest request = new JqGridRequest();
        request.setSelectColumns("fullname as name", "name as code", "name as id");
        if(StringUtils.isNotBlank(department_path)) {
            request.addFilterRule("department_treenode_path", JqGridFilterRuleOp.bw, department_path);
        }
        //request.addFilterRule("name", JqGridFilterRuleOp.in, "SELECT  app_user_name FROM app_user_role ");
        //request.addFilterRule("name", JqGridFilterRuleOp.isnotnull, "");
        request.addFilterRule("enable", JqGridFilterRuleOp.eq, "1");

        return this.appUserService.findAllDetailByRequest(request).getContent();
    }
    
    /**
     * 获取用户
     */
    @RequestMapping("cusUser")
    @ResponseBody
    public List<Map<String, Object>> cusUser(String username, String department_path) {
        JqGridRequest request = new JqGridRequest();
        request.setSelectColumns("fullname as name", "name as code", "id");
        if(StringUtils.isNotBlank(department_path)) {
            request.addFilterRule("department_treenode_path", JqGridFilterRuleOp.bw, department_path);
        }
        //request.addFilterRule("name", JqGridFilterRuleOp.in, "SELECT  app_user_name FROM app_user_role ");
        //request.addFilterRule("name", JqGridFilterRuleOp.isnotnull, "");
        request.addFilterRule("enable", JqGridFilterRuleOp.eq, "1");

        return this.appUserService.findAllDetailByRequest(request).getContent();
    }

    @Autowired
    private AppUserService appUserService;

    /**
     * 获取用户的管理关联项目
     */
    @RequestMapping("project")
    @ResponseBody
    public List<Map<String, Object>> project(String username, String userId) {
    	String sql = "SELECT MAX(data_range) FROM `app_user` a LEFT JOIN app_user_role b ON a.name = b.`app_user_name` LEFT JOIN app_role c ON b.`app_role_id`=c.`id` " +
    			"WHERE a.id='"+userId+"'";
    	String sql1 = "select id,name from proj_project";
    	JdbcTemplate jdbcTemplate = ContextHolder.getSpringBean("jdbcTemplate");
    	String dataRange = jdbcTemplate.queryForList(sql,String.class).get(0);
    	List<Map<String, Object>> projectList = jdbcTemplate.queryForList(sql1);
    	if("1111".equals(dataRange)){
    		return projectList;
    	}
        List<Map<String, Object>> list = appUserService.findUserProjects(userId);
        if (list.size() > 0) {
            return list;
        } else {
            return this.appUserService.findMembersProjectByUserId(userId);
        }
    }

    @Autowired
    private AppDepartmentService appDepartmentService;

    /**
     * 获取当前用户
     */
    @RequestMapping("currentUser")
    @ResponseBody
    public Map<String, Object> currentUser(String username) {
        Map<String, Object> user = appUserService.findOneDetailByUsername(username);
        Map<String, Object> result = new HashMap<>();
        result.put("fullname", user.get("fullname"));
        result.put("tel", user.get("tel"));
        result.put("mobile", user.get("mobile"));
        result.put("email", user.get("email"));
        return result;
    }

    /**
     * 获取当前用户
     */
    @RequestMapping("getUserInfo")
    @ResponseBody
    public Map<String, Object> getUserInfo(String username, String userInfo) {
        Map<String, Object> user = appUserService.findOneDetailByUsername(userInfo);
        Map<String, Object> result = new HashMap<>();
        result.put("id", user.get("id"));
        result.put("fullname", user.get("fullname"));
        result.put("tel", user.get("tel"));
        result.put("mobile", user.get("mobile"));
        result.put("email", user.get("email"));
        return result;
    }

    @Autowired
    private BpmProcessRunService bpmProcessRunService;

    @RequestMapping("submitUser")
    @ResponseBody
    public List<AppUser> submitUser(String username, String key, String processId, String nextTaskId, String
            businessKey, int processMode) {
        Collection<IUser> users = bpmProcessRunService.getNextSetpUser(key, processId, nextTaskId, businessKey, username, processMode);

        List<IUser> ul = new ArrayList<>();
        ul.addAll(users);
        Collections.sort(ul, new Comparator<IUser>() {
            @Override
            public int compare(IUser o1, IUser o2) {
                // 根据用户汉字姓名排序
                return Collator.getInstance(java.util.Locale.CHINA).compare(o1.getFullname(), o2.getFullname());
            }
        });

        List<AppUser> result = new ArrayList<>();
        for (IUser user : ul) {
            AppUser appUser = new AppUser();
            appUser.setFullname(user.getFullname());
            appUser.setName(user.getUsername());
            result.add(appUser);
        }
        return result;
    }


    /**
     * 获取用户
     */
    @RequestMapping("submitUserSelect")
    @ResponseBody
    public List<Map<String, Object>> submitUserSelect(String username, String department_path, String key, String
            processId, String nextTaskId, String businessKey, int processMode) {
        List<AppUser> appUsers = this.submitUser(username, key, processId, nextTaskId, businessKey, processMode);

        JqGridRequest request = new JqGridRequest();
        request.setSelectColumns("fullname as name", "name as id");
        request.addFilterRule("department_treenode_path", JqGridFilterRuleOp.bw, department_path);
        request.addFilterRule("name", JqGridFilterRuleOp.in, "SELECT  app_user_name FROM app_user_role ");
        request.addFilterRule("name", JqGridFilterRuleOp.isnotnull, "");
        request.addFilterRule("enable", JqGridFilterRuleOp.eq, "1");

        if (!appUsers.isEmpty()) {
            String inNamesStr = "";
            for (AppUser appUser : appUsers) {
                inNamesStr += "'" + appUser.getUsername() + "',";
            }
            inNamesStr = inNamesStr.substring(0, inNamesStr.length() - 1);
            request.setSearchString(" a.name in(" + inNamesStr + ")");
        }

        return this.appUserService.findAllDetailByRequest(request).getContent();
    }

    @Autowired
    private ConfCategoryService confCategoryService;

    /**
     * 获取部门
     */
    @RequestMapping("ciCategory")
    @ResponseBody
    public List<ConfCategory> ciCategory(String username) {
        List<ConfCategory> tree = confCategoryService.getTree(null, false, "id", "name", "parent_id", "treenodePath");
        return tree;
    }

    @Autowired
    private ConfCiService confCiService;

    /**
     * 获取用户
     */
    @RequestMapping("ci")
    @ResponseBody
    public List<Map<String, Object>> ci(String username, String path) {
        JqGridRequest request = new JqGridRequest();
        request.setSelectColumns("name", "code", "id");
        request.addFilterRule("treenode_path", JqGridFilterRuleOp.bw, path);

        List<Map<String, Object>> result = this.confCiService.findAllDetailByRequest(request).getContent();
        return result;
    }

    @RequestMapping("trace")
    @ResponseBody
    public List<Map<String, Object>> trace(String username, String processId) {

        List<Map<String, Object>> trace = new ArrayList<>();

        Map<String, Object> map = bpmProcessRunService.trace(processId);

        List<Map<String, Object>> historys = (List<Map<String, Object>>) map.get("historys");
        for (Map<String, Object> history : historys) {
            String name = (String) history.get("name_");
            if (StringUtils.isEmpty(name)) {
                name = "开始";
            }
            Map<String, Object> node = new HashMap<>();
            node.put("name", name);
            node.put("action_time", history.get("action_time"));
            node.put("action_name", history.get("action_name"));
            node.put("fullname", history.get("fullname"));
            trace.add(node);
        }

        String areRunning = (String) map.get("areRunning");
        if (StringUtils.isNotEmpty(areRunning)) {

            String currentTaskName = (String) map.get("currentTaskName");
            if (StringUtils.isNotEmpty(currentTaskName)) {

                List<Map<String, Object>> listUser = (List<Map<String, Object>>) map.get("currentUserList");
                List<String> listUserName = new ArrayList<>();
                String fullnames="";
                for (Map<String, Object> user : listUser) {

                    listUserName.add((String) user.get("fullname"));
                    fullnames+=(String) user.get("fullname")+",";
                }
                fullnames=fullnames.substring(0,fullnames.length()-1);

                Map<String, Object> node = new HashMap<>();
                node.put("name", currentTaskName);
                node.put("action_time", null);
                node.put("action_name", null);
               // node.put("fullname", String.join(",", listUserName));jdk8
                node.put("fullname", fullnames);
                trace.add(node);
            }
        }
        return trace;
    }
}
